#include "junix.h"

char *jreadline_r(int fd, char *buf, size_t sz)
{
	int ch,i;
	ssize_t size=0;
	char *p=buf,*q=buf;

	if(buf==NULL)
	{
		q=malloc(LINE_MAX);
		p=q;
	}

	for(i=0; i<sz-2; i++)
	{
		while( (size=read(fd,&ch,1))==-1 && (errno == EINTR) )
		{}

		if(size==-1)
			err_sys("read");
		else if(!size)
		{
			if(p==q)
			{
				if(q!=buf)
					free(q);
				return NULL;
			}

			*p++ = '\n';
			break;
		}else{
			*p++ = ch;
			if(ch=='\n')
				break;
		}
	}

	if(*(p-1)=='\n')
		*p = '\0';
	else{
        *p++='\n';
		*p='\0';
	}

	return q;
}

int main(int argc, char **argv)
{
	int fd=Open("XXX",O_RDONLY);
	char buf[LINE_MAX];

	while(jreadline_r(fd,buf,LINE_MAX) != NULL)
		printf("%s",buf);

	exit(0);
}

